package com.intelligentpension.bleconnect

import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.hjq.toast.ToastUtils
import com.permissionx.guolindev.PermissionX
import java.lang.reflect.Method

class MainActivity : AppCompatActivity(), BLRReceiver.diveceListen {
    private var mBle: BluetoothAdapter? = null
    private var receiver: BLRReceiver? = null
    private var list: MutableList<BluetoothDevice> = ArrayList()
    private lateinit var mRecyclerView: RecyclerView
    private lateinit var mAdapter: ItemAdapter;
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        mRecyclerView = findViewById<RecyclerView>(R.id.recycler)

        var manger = LinearLayoutManager(this)
        mRecyclerView.layoutManager = manger
        mAdapter = ItemAdapter(R.layout.item_layout, list)
        mRecyclerView.adapter = mAdapter

        PermissionX.init(this@MainActivity).permissions(
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.BLUETOOTH_ADVERTISE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.BLUETOOTH_SCAN,
            Manifest.permission.BLUETOOTH_CONNECT,
            Manifest.permission.BLUETOOTH,
            Manifest.permission.BLUETOOTH_ADMIN
        ).onForwardToSettings { scope, deniedList ->
            scope.showForwardToSettingsDialog(
                deniedList,
                "You need to allow necessary permissions in Settings manually",
                "OK",
                "Cancel"
            )
        }.request { allGranted, _, deniedList ->
            if (allGranted) {
                Toast.makeText(this, "All permissions are granted", Toast.LENGTH_LONG).show()
            } else {
                Toast.makeText(
                    this, "These permissions are denied: $deniedList", Toast.LENGTH_LONG
                ).show()
            }
        }


        mBle = (getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager).adapter
        if (mBle == null) {
            ToastUtils.show("当前设备不支持蓝牙")
            return
        } else {

            if (mBle!!.isEnabled) {
                //只有sdk大于30的时候,才会需要这个权限
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                    if (ActivityCompat.checkSelfPermission(
                            this, Manifest.permission.BLUETOOTH_CONNECT
                        ) != PackageManager.PERMISSION_GRANTED
                    ) {
                        ToastUtils.show("当前没有权限Manifest.permission.BLUETOOTH_CONNECT")
                        return
                    }
                }
                mBle!!.enable()
            }

            //查看本机是否支持BLE蓝牙
            if (!packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
                ToastUtils.show("本机不支持BLE低功耗蓝牙")
                return
            }

            //获取当前已经配对的蓝牙
            var bondedDevices = mBle!!.bondedDevices
            for (dev in bondedDevices.iterator()) {
                if (!list.contains(dev)) {
                    list.add(dev)
                }
            }
            mAdapter.notifyDataSetChanged()

            // Register for broadcasts when a device is discovered
            val filter = IntentFilter()
            filter.addAction(BluetoothDevice.ACTION_FOUND)
            filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED)
            receiver = BLRReceiver(this@MainActivity)
            //注册广播(动态注册广播,不许要在清单文件中说明)
            registerReceiver(receiver, filter)

            mBle!!.startDiscovery()//设备开始查找设备
        }

        //设置条目的点击时间
        mAdapter.setOnItemClickListener { _, _, position ->
            var bluetoothDevice = list[position]

            //TODO:如果没有配对的话,进行配对
            if (bluetoothDevice.bondState != BluetoothDevice.BOND_BONDED) run {

                //TODO:蓝牙自动配对
                // 自动配对就是通过反射去调用 BluetoothDevice 的 createBond 方法
                val createBondMethod: Method = BluetoothDevice::class.java.getMethod("createBond")
                createBondMethod.invoke(bluetoothDevice)
            }

            //TODO:根据蓝牙的分类,是经典蓝牙还是BLE低功耗蓝牙
            when (bluetoothDevice.type) {
                BluetoothDevice.DEVICE_TYPE_CLASSIC -> {
                    ToastUtils.show("这是普通蓝牙")
                }
                BluetoothDevice.DEVICE_TYPE_LE -> {
                    skipOther(bluetoothDevice)
                }
                BluetoothDevice.DEVICE_TYPE_DUAL-> {
                    skipOther(bluetoothDevice)
                    ToastUtils.show("这是低功耗蓝牙")
                }
                else ->{
                    ToastUtils.show("这他么不知道什么类型")
                }
            }

        }
    }

    //注册广播,当监听到蓝牙变化的时候,进行刷新
    override fun found(dev: BluetoothDevice?) {
        if (dev != null && !list.contains(dev)) {
            list.add(dev)
        }
        mAdapter.notifyDataSetChanged()
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(receiver)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            if (ActivityCompat.checkSelfPermission(
                    this, Manifest.permission.BLUETOOTH_SCAN
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                return
            }
        }
        mBle?.cancelDiscovery()
    }

    fun skipOther(bluetoothDevice: BluetoothDevice) {
        ToastUtils.show("这是低功耗蓝牙")
        Intent(this@MainActivity,LowpowerActivity::class.java).apply {
            putExtra(ContectUtils.EXTRAS_DEVICEST,bluetoothDevice)
            putExtra(ContectUtils.EXTRAS_UART,ContectUtils.EXTRAS_UART)
            putExtra(ContectUtils.EXTRAS_TXO,ContectUtils.EXTRAS_TXO)
            putExtra(ContectUtils.EXTRAS_RXI,ContectUtils.EXTRAS_RXI)
            startActivity(this)
        }
    }
}